-- 爆炸投射物

local MissionWeapon = TaleWorlds.MountAndBlade.MissionWeapon
local BlowFlags = TaleWorlds.MountAndBlade.BlowFlags

local onlyPlayer = true
local exp_range = 5
local behavior

return {
onBeforeMissionBehaviorInitialize = function (mission)
    behavior = SubModule:CreateMissionBehavior({
        onMissileHit = function (attacker, victim, isCanceled, collisionData)
            if onlyPlayer and not attacker.IsMainAgent then
                return
            end

            local missile = SubModule:GetMissile(collisionData.AffectorWeaponSlotOrMissileIndex)
            if missile == nil then
                return
            end

            local weapon = missile.Weapon
            if weapon == MissionWeapon.Invalid or weapon.CurrentUsageItem == nil then
                return
            end

            local pos = collisionData.CollisionGlobalPosition
            local identity = Mat3.Identity
            identity.f = collisionData.WeaponBlowDir
            identity:Orthonormalize()
            mission:AddParticleSystemBurstByName("psys_burning_projectile_water_coll", MatrixFrame(identity, pos), true)
            mission:AddParticleSystemBurstByName("psys_game_ballistamissile_default_coll", MatrixFrame(identity, pos), true)
            mission:MakeSoundOnlyOnRelatedPeer(SoundEvent.GetEventIdFromString("event:/mission/combat/impact/burning_jar/default"), pos, attacker.Index)
            mission:AddSoundAlarmFactorToAgents(attacker.Index, pos, 15)

            local b = SubModule:CreateMissileBlow(attacker, collisionData, weapon, pos, attacker.Position)
            if b.OwnerId ~= attacker.Index then
                return
            end

            b.BlowFlag = BlowFlags.NoSound

            local agents = SubModule:CreateAgentList()
            mission:GetNearbyAgents(pos.AsVec2, exp_range, agents)
            for i = 0, agents.Count - 1, 1 do
                local agent = agents[i]
                if agent ~= attacker and (agent:IsEnemyOf(attacker) or agent:IsFriendOf(attacker)) then
                    b.InflictedDamage = MBRandom.RandomInt(99, 150)
                    agent:RegisterBlow(b, collisionData)
                end
            end
        end
    })
    mission:AddMissionBehavior(behavior)
end
}